<?php

namespace app\api\controller;

use addons\shopro\service\pay\PayOper;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\DailyPerformance;
use app\admin\model\RechargeCorrectLog;
use app\admin\model\shopro\Bonus;
use app\admin\model\shopro\BonusLog;
use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\commission\Level;
use app\admin\model\shopro\commission\MonthlyCompliance;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use app\admin\model\shopro\Pclog;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\trade\Order as TradeOrderModel;
use app\admin\model\shopro\user\User;
use app\admin\model\shopro\user\WalletLog;
use app\common\controller\Api;
use Exception;
use think\Db;
use think\Request;
use addons\shopro\service\commission\Agent as AgentService;

/**
 * 定时任务接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     *达标奖计算
     *每月开始第一天00.00执行
     */
    public function monthly()
    {
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_monthly', false);//月度达标奖配置
        //月度达标奖计算 start
        //["compliance"]
        $monthly = MonthlyCompliance::whereTime("day_time", "last month")->find();
        if (!empty($configs) && !empty($configs["compliance"]) && empty($monthly)) {
            \think\Queue::push('\addons\shopro\job\Monthly@index', [
                'user_id' => 1
            ], 'shopro');
        }
        //月度达标奖计算 end
    }

    public function dividend_test()
    {
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        $user=User::alias("user")
            ->join("shopro_commission_agent agent","user.id=agent.user_id")
            ->where(["user.user_id"=>"52544"])
            ->order("dividend_level_time","asc")
            ->find();//查找等级满足分红接力赛用户
        if(!empty($user)){
            $parent_user_id=\app\common\model\User::where("parent_user_id",$user["id"])->column("id");
            if(!empty($parent_user_id)){
                $now_time=strtotime(date("Y-m-d",time()));
                $user_bonus=(new \app\admin\model\shopro\user\Bonus)->where(["user_id"=>$user["id"]])->order("createtime","desc")->find();
                if(!empty($user_bonus)){
                    //之前已经分红--时间从上次分红时间推算
                    $time=strtotime(date("Y-m-d",strtotime($user_bonus["createtime"])));
                }else{
                    $time=strtotime(date("Y-m-d",strtotime("-6 month")));
                    $user["dividend_level_time"]=strtotime(date("Y-m-d",$user["dividend_level_time"]));
                    if($user["dividend_level_time"]<$time){
                        //如果已经超过半年时间
                        $time=$user["dividend_level_time"];
                    }
                }
                $where["createtime"]=["between",[$time,$now_time]];
                $where_dividend["is_dividend"]=["=",1];
//                    $where_dividend["is_self"]=["=",0];
                $order_ids=Performance::field("GROUP_CONCAT(DISTINCT order_id) money")
                    ->where($where)
                    ->where($where_dividend)
                    ->buildSql();
                $self_performance_data = Performance::field("sum(money) money")
                    ->where(["user_id"=>$user["id"]])
                    ->where($where)
                    ->where($where_dividend)
                    ->union([$order_ids], true)
                    ->select();//所有
                $self_performance=$self_performance_data[0]["money"]??0;
                if(!empty($user_bonus)){
                    //之前已经分红--加上上次结余业绩
                    $self_performance=bcadd(bcadd($self_performance,$user_bonus["big_money"]),$user_bonus["small_money"]);
                }
                if($self_performance>=1000000){
                    $ids=$self_performance_data[1]["money"]??0;
                    $list = Performance::whereIn("user_id",$parent_user_id)
                        ->field("sum(money) money,user_id")
                        ->where($where)
                        ->whereIn("order_id",$ids)
                        ->group("user_id")
                        ->select();
                    if(!empty($list)){
                        $big_market=0;
                        $market=0;
                        foreach ($list as $v){
                            $big_market = max($big_market , $v['money']);
                            $market+=$v["money"];
                        }
                        $small_market=bcsub($market,$big_market,2);
                        $big_market=bcadd($user_bonus["big_money"]??0,$big_market,2);//加上上次结余大市场业绩
                        $small_market=bcadd($user_bonus["small_money"]??0,$small_market,2);//加上上次结余小市场业绩
                        if($small_market>=200000){
                            //小市场大于20w
                            $bonus=Bonus::find();//奖金池
                            if($bonus && $bonus["money"]>0){
                                $bonus_money=bcmul($bonus["money"],($configs["divvy_rate"]/100),2);//分红金额
                                //变更用户余额
                                if($small_market>=1000000){
                                    //小市场大于等于100w
                                    $small_money_money=0;
                                    $small_market_cut=1000000;
                                    $small_money=bcsub($small_market,1000000,2);//小市场结余金额
                                }else{
                                    $small_money=0;
                                    $small_money_money=bcsub(1000000,$small_market,2);//小市场扣除之后还剩余多少
                                    $small_market_cut=$small_market;
                                }
                                if($small_money_money>0){
                                    /*$big_market_cut=bcsub($big_market,$small_money_money,2);//大市场剩余
                                    $big_market_cut=bcsub($big_market,$big_market_cut,2);//大市场扣除*/
                                    $big_market_cut=$small_money_money;
                                    $big_money=bcsub($big_market,$big_market_cut,2);//大市场结余金额
                                }else{
                                    $big_market_cut=0;
                                    $big_money=$big_market;
                                }
                                if($bonus_money>0){
                                    $ext=[
                                        "big_money"=>$big_money,//大市场结余金额，
                                        "small_money"=>$small_money,//小市场结余金额，
                                        "big_market"=>$big_market_cut,//大市场扣除金额
                                        "small_market"=>$small_market_cut,//小市场扣除金额
                                        "bonus"=>$bonus_money,//分红金额
                                        "bonus_money"=>$bonus["money"],//奖金池金额
                                        "divvy_rate"=>$configs["divvy_rate"],//分红比例
                                    ];
//                                    WalletService::change($user["id"], "money", $bonus_money, 'money_dividend', [], "分红接力赛收益");
//                                    $bonus->setDec("money",$bonus_money);
                                    $logModel= new BonusLog();
//                                    $logModel->save([
//                                        "money"=>-$bonus_money,
//                                        "order_id"=>0,
//                                        "order_pv"=>$bonus["money"],
//                                        "user_id"=>$user["id"],
//                                        "createtime"=>time(),
//                                        "momo"=>"分红接力赛收益发放",
//                                        "order_no"=>0,
//                                        "type"=>1,
//                                        "ratio"=>$configs["divvy_rate"],
//                                        "order_details"=>json_encode($ext),
//                                    ]);
                                    //生成分红记录
                                    $bonus=(new \app\admin\model\shopro\user\Bonus)->create([
                                        "user_id"=>$user["id"],
                                        "big_money"=>$big_money,//大市场结余金额，
                                        "small_money"=>$small_money,//小市场结余金额，
                                        "big_market"=>$big_market_cut,//大市场扣除金额
                                        "small_market"=>$small_market_cut,//小市场扣除金额
                                        "bonus"=>$bonus_money,//分红金额
                                        "ext"=>json_encode($ext),//分红金额
                                    ]);
                                    //记录平台支出
//                                    Pclog::create([
//                                        "order_id"=>$bonus["id"],
//                                        "money"=>-$bonus_money,
//                                        "type"=>3,
//                                        "pv_price"=>$bonus["bonus"],
//                                        "ext"=>$ext,
//                                        "user_id"=>$user["id"],
//                                        "createtime"=>time(),
//                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 充正
     * */
    /* public function rechargeCorrect()
     {
         $user = User::with(['agent' => function ($query) {
             return $query->with('level_info');
         }])
             ->where("payment_goods<0")->find();
         if (!empty($user)) {
             $user_ids=User::alias("user")
                 ->join("user t2","user.id=t2.parent_user_id","left")
                 ->where("t2.id is null")
                 ->column("user.id");
             $user_data = User::whereIn("id",$user_ids)->select();//查找最底层用户
             if (!empty($user_data)) {
                 foreach ($user_data as $v) {
                     \think\Queue::push('\addons\shopro\job\RechargeCorrect@index', [
                         'user_id' => $v["id"]
                     ], 'shopro');
                 }
             }
         }
     }*/
    /**
     * 充正
     * */
    public function rechargeCorrect()
    {
        $Ok_redis_key = 'rechargeCorrectOk|user';
        redis_cache()->delete($Ok_redis_key);
        $user = User::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where("payment_goods<0")->find();
        if (!empty($user)) {
            $user_ids = User::alias("user")
                ->join("user t2", "user.id=t2.parent_user_id", "left")
                ->where("t2.id is null")
                ->column("user.id");
            //$user_data = User::whereIn("id",$user_ids)->select();//查找最底层用户
            if (!empty($user_ids)) {
                foreach ($user_ids as $v) {
                    \think\Queue::push('\addons\shopro\job\RechargeCorrect@index', [
                        'user_id' => $v
                    ], 'shopro');
                }
            }
        }
    }

    /*新充正*/
    public function rechargeCorrect1()
    {
        $user_ids = User::alias("user")
            ->join("user t2", "user.id=t2.parent_user_id", "left")
            ->where("t2.id is null")
            ->column("user.id");
        $haveParent = true;
        $data = $user_ids;
        $childData = $user_ids;
        while ($haveParent) {
            $childData = $this->get_parent($childData);
            if (count($childData) < 1) {
                $haveParent = false;
            } else {
                $data = array_merge($data, $childData);
            }
        }
        redis_cache("rectification_data", json_encode($data), 3600);
        $count = ceil(count($data) / 100);
        while ($count > 0) {
            \think\Queue::push('\addons\shopro\job\RechargeCorrect@index1', [
                'count' => $count
            ], 'shopro');
            $count--;
        }
        echo "success:count:{$count}";
    }

    //获取直属上级
    public function get_parent($idArr)
    {
        $user_ids = User::alias("user")
            ->whereIn("id", $idArr)
            ->where("parent_user_id > 0")
            ->distinct("parent_user_id")
            ->column("parent_user_id");
        return $user_ids;
    }
    /*public function rechargeCorrect()
    {
        $user = User::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where("payment_goods<0")->find();
        if (!empty($user)) {
            \think\Queue::push('\addons\shopro\job\RechargeCorrect@index', [
                'user_id' => $user["id"]
            ], 'shopro');
        }
    }*/

    /**
     * 分红接力赛
     * */
    public function dividend()
    {
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        if ($configs["status"]) {
            $user = User::alias("user")
                ->join("shopro_commission_agent agent", "user.id=agent.user_id")
                ->where(["agent.level" => $configs["level"], "is_dividend" => 1])
                ->where("dividend_level_time is not null")
                ->order("dividend_level_time", "asc")
                ->find();//查找等级满足分红接力赛用户
            /*$configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
            if(!empty($user)){
                foreach($user as $user){
                    $parent_user_id=\app\common\model\User::where("parent_user_id",$user["id"])->column("id");
                    if(!empty($parent_user_id)){
                        $now_time=strtotime(date("Y-m-d",time()));
                        $user_bonus=(new \app\admin\model\shopro\user\Bonus)->where(["user_id"=>$user["id"]])->where("id=5")->order("createtime","desc")->find();

                        if(!empty($user_bonus)){
                            //之前已经分红--时间从上次分红时间推算
                            $time=strtotime(date("Y-m-d",strtotime($user_bonus["createtime"])));
                        }else{
                            $time=strtotime(date("Y-m-d",strtotime("-6 month")));
                            $user["dividend_level_time"]=strtotime(date("Y-m-d",$user["dividend_level_time"]));
                            if($user["dividend_level_time"]<$time){
                                //如果已经超过半年时间
                                $time=$user["dividend_level_time"];
                            }
                        }
                        $where["createtime"]=["between",[$time,$now_time]];
                        $where_dividend["is_dividend"]=["=",1];
                        $where_dividend["is_self"]=["=",0];
                        $order_ids=Performance::field("GROUP_CONCAT(DISTINCT order_id) money")
                            ->where($where)
                            ->where($where_dividend)
                            ->buildSql();
                        $self_performance_data = Performance::field("sum(money) money")
                            ->where(["user_id"=>$user["id"]])
                            ->where($where)
                            ->where($where_dividend)
                            ->union([$order_ids], true)
                            ->select();//所有
                        $self_performance=$self_performance_data[0]["money"]??0;
                        if(!empty($user_bonus)){
                            //之前已经分红--加上上次结余业绩
                            $self_performance=bcadd(bcadd($self_performance,$user_bonus["big_money"]),$user_bonus["small_money"]);
                        }
                        if($self_performance>=1000000){
                            $ids=$self_performance_data[1]["money"]??0;
                            $list = Performance::whereIn("user_id",$parent_user_id)
                                ->field("sum(money) money,user_id")
                                ->where($where)
                                ->whereIn("order_id",$ids)
                                ->group("user_id")
                                ->select();
                            if(!empty($list)){
                                $big_market=0;
                                $market=0;
                                foreach ($list as $v){
                                    $big_market = max($big_market , $v['money']);
                                    $market+=$v["money"];
                                }
                                $small_market=bcsub($market,$big_market,2);
                                $big_market=bcadd($user_bonus["big_money"]??0,$big_market,2);//加上上次结余大市场业绩
                                $small_market=bcadd($user_bonus["small_money"]??0,$small_market,2);//加上上次结余小市场业绩
                                if($small_market>=200000){
                                    //小市场大于20w
                                    $bonus=Bonus::find();//奖金池
                                    if($bonus && $bonus["money"]>0){
                                        $bonus_money=bcmul($bonus["money"],($configs["divvy_rate"]/100),2);//分红金额
                                        //变更用户余额
                                        if($small_market>=1000000){
                                            //小市场大于等于100w
                                            $small_money_money=0;
                                            $small_market_cut=1000000;
                                            $small_money=bcsub($small_market,1000000,2);//小市场结余金额
                                        }else{
                                            $small_money=0;
                                            $small_money_money=bcsub(1000000,$small_market,2);//小市场扣除之后还剩余多少
                                            $small_market_cut=$small_market;
                                        }
                                        if($small_money_money>0){
                                            $big_market_cut=$small_money_money;
                                            $big_money=bcsub($big_market,$big_market_cut,2);//大市场结余金额
                                        }else{
                                            $big_market_cut=0;
                                            $big_money=$big_market;
                                        }
                                        if($bonus_money>0){
                                            $ext=[
                                                "big_money"=>$big_money,//大市场结余金额，
                                                "small_money"=>$small_money,//小市场结余金额，
                                                "big_market"=>$big_market_cut,//大市场扣除金额
                                                "small_market"=>$small_market_cut,//小市场扣除金额
                                                "bonus"=>$bonus_money,//分红金额
                                                "bonus_money"=>$bonus["money"],//奖金池金额
                                                "divvy_rate"=>$configs["divvy_rate"],//分红比例
                                            ];
                                            WalletService::change($user["id"], "money", $bonus_money, 'money_dividend', [], "分红接力赛收益");
                                            $bonus->setDec("money",$bonus_money);
                                            $logModel= new BonusLog();
                                            $logModel->save([
                                                "money"=>-$bonus_money,
                                                "order_id"=>0,
                                                "order_pv"=>0,
                                                "order_details"=>'',
                                                "user_id"=>$user["id"],
                                                "createtime"=>time(),
                                                "momo"=>"分红接力赛收益发放",
                                                "order_no"=>0,
                                                "type"=>1,
                                                "ratio"=>$configs["divvy_rate"],
                                            ]);
                                            //生成分红记录
                                            (new \app\admin\model\shopro\user\Bonus)->save([
                                                "user_id"=>$user["id"],
                                                "big_money"=>$big_money,//大市场结余金额，
                                                "small_money"=>$small_money,//小市场结余金额，
                                                "big_market"=>$big_market,//大市场扣除金额
                                                "small_market"=>$small_market,//小市场扣除金额
                                                "bonus"=>$bonus_money,//分红金额
                                                "ext"=>json_encode($ext),//分红金额
                                            ]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            die();*/
            if (!empty($user)) {
                \think\Queue::push('\addons\shopro\job\Dividend@index', [
                    'user_id' => $user["id"]
                ], 'shopro');
            }
        }
    }
    public function check(){
        /*for ($i=25; $i<=31; $i++)
        {
            $data=[strtotime("2024-1-".$i." 00:00:00"),strtotime("2024-1-".$i." 23:59:59")];
            $this->dailyPerformance2($data);
        }*/
        for ($i=1; $i<=1; $i++)
        {
            $data=[strtotime("2024-2-".$i." 00:00:00"),strtotime("2024-2-".$i." 23:59:59")];
            $this->dailyPerformance2($data);
        }
    }

    public function dailyPerformance2($data)
    {
        $yesterday = DailyPerformance::whereTime("createtime", 'between', $data)->find();
        $last_time_data = $data;
        $order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment,sum(pv_price) pv_price,sum(goods_amount) paygoods_price,sum(dispatch_amount) freight,sum(total_discount_fee) total_discount_fee")
            ->whereBetween("createtime", $last_time_data)->whereIn("status", ["paid", "completed"])->find();
        //留存-向平台进货的金额-每笔订单pv值*3%-平台给出平级奖
        $wallet = WalletLog::where(["type" => "money", "event" => "money_payment", "flow_id" => 0])
            ->where("amount<0")
            ->whereBetween("createtime", $last_time_data)->sum("amount");//向平台进货金额
        $equal = WalletLog::where(["type" => "money", "event" => "money_payment_cut_income", "flow_id" => 0])
            ->where("amount>0")
            ->whereBetween("createtime", $last_time_data)->sum("amount");//平台给出平级奖
        $pv_price = $order["pv_price"] ?? 0;
        $price = bcmul($pv_price, 0.03, 2);
        $individuality_price = bcmul($pv_price, 0.05, 2);
        $retail = $order["retail"] ?? 0;
        $payment = $order["payment"] ?? 0;
        $retained = $wallet ?? 0;
        $paygoods_price = $order["paygoods_price"] ?? 0;
        $freight = $order["freight"] ?? 0;
        $total_discount_fee = $order["total_discount_fee"] ?? 0;
        $retained = bcsub(abs($retained), (bcadd($price, $equal)), 2);
        $retained = bcadd($retained, (bcsub($retail, ($order["pv_price"] ?? 0), 2)), 2);//(新增 +每笔订单零售价-pv值)
        $retained = bcsub($retained, $individuality_price, 2);//(新增 -每笔订单pv值*5)
        $order = new Order();
        $item = OrderItem::where('order_id=' . $order->getTable() . '.id')->fetchSql()
            ->whereBetween("updatetime", $last_time_data)
            ->where('refund_status', '=', 2)->column("order_id");
        $return_order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment")
            ->whereIn("status", ['paid', 'completed'])
            ->where("EXISTS (" . $item . ")")->find();//昨天退款
        $return_retail = $return_order["retail"] ?? 0;//昨天退款原价
        $return_payment = $return_order["payment"] ?? 0;//昨天退款支付金额
        if (!empty($return_order)) {
            $retail = bcsub($retail, $return_retail, 2);
            $payment = bcsub($payment, $return_payment, 2);
        }
        if (empty($yesterday)) {
            DailyPerformance::create([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"] ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" => strtotime("-1 days", time()),
                "pc_paygoods" => (abs($wallet)) ?? 0,
                "pc_equal" => $equal ?? 0,
                "pc_bonus" => $price ?? 0,
                "pc_individual" => $individuality_price ?? 0,
                "pv_price" => $pv_price,
                "paygoods_price" => $paygoods_price,
                "freight" => $freight,
                "total_discount_fee" => $total_discount_fee,
                "createtime"=>$data[0],
            ]);
        } else {
            $yesterday->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"] ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" => strtotime("-1 days", time()),
                "pc_paygoods" => (abs($wallet)) ?? 0,
                "pc_equal" => $equal ?? 0,
                "pc_bonus" => $price ?? 0,
                "pc_individual" => $individuality_price ?? 0,
                "pv_price" => $pv_price,
                "paygoods_price" => $paygoods_price,
                "freight" => $freight,
                "total_discount_fee" => $total_discount_fee,
                "createtime"=>$data[0],
            ]);
        }
        //月度达标奖计算 end
    }
    /**
     *每日业绩统计
     *每天00.00执行
     */
    public function dailyPerformance()
    {
        $yesterday = DailyPerformance::whereTime("createtime", "yesterday")->find();
        //$yesterday = DailyPerformance::whereTime("createtime", 'between', [1706198400,1706284799])->find();
        $last_time = strtotime(date("Y-m-d", strtotime("-1 days", time())));//昨天天时间
        $last_time_data = [$last_time, strtotime(date("Y-m-d", time()))];
        $order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment,sum(pv_price) pv_price,sum(goods_amount) paygoods_price,sum(dispatch_amount) freight,sum(total_discount_fee) total_discount_fee")
            ->whereBetween("createtime", $last_time_data)->whereIn("status", ["paid", "completed"])->find();
        //留存-向平台进货的金额-每笔订单pv值*3%-平台给出平级奖
        $wallet = WalletLog::where(["type" => "money", "event" => "money_payment", "flow_id" => 0])
            ->where("amount<0")
            ->whereBetween("createtime", $last_time_data)->sum("amount");//向平台进货金额
        $equal = WalletLog::where(["type" => "money", "event" => "money_payment_cut_income", "flow_id" => 0])
            ->where("amount>0")
            ->whereBetween("createtime", $last_time_data)->sum("amount");//平台给出平级奖
        $pv_price = $order["pv_price"] ?? 0;
        $price = bcmul($pv_price, 0.03, 2);
        $individuality_price = bcmul($pv_price, 0.05, 2);
        $retail = $order["retail"] ?? 0;
        $payment = $order["payment"] ?? 0;
        $retained = $wallet ?? 0;
        $paygoods_price = $order["paygoods_price"] ?? 0;
        $freight = $order["freight"] ?? 0;
        $total_discount_fee = $order["total_discount_fee"] ?? 0;
        $retained = bcsub(abs($retained), (bcadd($price, $equal)), 2);
        $retained = bcadd($retained, (bcsub($retail, ($order["pv_price"] ?? 0), 2)), 2);//(新增 +每笔订单零售价-pv值)
        $retained = bcsub($retained, $individuality_price, 2);//(新增 -每笔订单pv值*5)
        /* dump([
             "retail" => $retail,
             "payment" => $payment,
             "retained" => $retained,//总留存
         ]);*/
        //$q_time = strtotime(date("Y-m-d", strtotime("-2 days", time())));//前天时间
        $order = new Order();
        $item = OrderItem::where('order_id=' . $order->getTable() . '.id')->fetchSql()
            ->whereBetween("updatetime", $last_time_data)
            ->where('refund_status', '=', 2)->column("order_id");
        $return_order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment")
            ->whereIn("status", ['paid', 'completed'])
            ->where("EXISTS (" . $item . ")")->find();//昨天退款
        $return_retail = $return_order["retail"] ?? 0;//昨天退款原价
        $return_payment = $return_order["payment"] ?? 0;//昨天退款支付金额
        if (!empty($return_order)) {
            $retail = bcsub($retail, $return_retail, 2);
            $payment = bcsub($payment, $return_payment, 2);
        }
        /*dump($order);
        dump($retail);
        dump($payment);
        dump($retained);
        dump($price);
        dump($equal);
        die();*/
        if (empty($yesterday)) {
            DailyPerformance::create([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"] ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" => strtotime("-1 days", time()),
                "pc_paygoods" => (abs($wallet)) ?? 0,
                "pc_equal" => $equal ?? 0,
                "pc_bonus" => $price ?? 0,
                "pc_individual" => $individuality_price ?? 0,
                "pv_price" => $pv_price,
                "paygoods_price" => $paygoods_price,
                "freight" => $freight,
                "total_discount_fee" => $total_discount_fee,
            ]);
        } else {
            $yesterday->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"] ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" => strtotime("-1 days", time()),
                "pc_paygoods" => (abs($wallet)) ?? 0,
                "pc_equal" => $equal ?? 0,
                "pc_bonus" => $price ?? 0,
                "pc_individual" => $individuality_price ?? 0,
                "pv_price" => $pv_price,
                "paygoods_price" => $paygoods_price,
                "freight" => $freight,
                "total_discount_fee" => $total_discount_fee,
            ]);
        }
        //月度达标奖计算 end
    }


    /**
     * 处理上下级关系
     * */
    public function check_agent()
    {
        $res = WalletService::findSideways(52285, 8, []);
        dump($res);
        die();
        $order = Order::find(97);
        $user = User::find($order["user_id"]);
        \think\Queue::push('\addons\shopro\job\OrderPaid@paid', ['order' => $order, 'user' => $user], 'shopro-high');
        die();
        /*        $parent_user_id=WalletService::checkAellAgent(
                    71669);
                dump($parent_user_id);die();*/
        WalletService::autorechargePayment(53864);
        die();
        $user = Agent::where(["level" => 8])->select();
        foreach ($user as $v) {

            (new AgentService($v["user_id"]))->runAgentUpgradePlan();
        }
        dump($user);
        die();
        die();
        $user = \app\admin\model\User::field("id")->order("id", "asc")->select();
        foreach ($user as $v) {
            \think\Queue::push('\addons\shopro\job\User@check_agent', ['user_id' => $v["id"]], 'shopro');
        }
    }

    public function find($id, $parent_user_id, $arr = [])
    {
        $user = \app\common\model\User::where(["parent_user_id" => $id])->select();
        if (!empty($user)) {
            foreach ($user as $v) {
                if (!empty($parent_user_id)) {
                    if ($v["id"] == $parent_user_id) {
                        //如果下级id等于上级的parent_user_id
                        /*\think\Log::info('data:'.json_encode($arr).' 我的上级是我的下级：[ID=' .  $parent_user_id. '&nickname=' . $v["nickname"] . '&parent_user_id='.$v["id"].'] ---Ended');
                        \app\common\model\User::where(["id"=>$v["parent_user_id"]])->update(["parent_user_id"=>0]);*/
                        continue;
                    }
                }
                if (in_array($v["parent_user_id"], $arr)) {
                    //如果下级的上级id在下级id数组中
                    /*\think\Log::info('data:'.json_encode($arr).'[ID=' . $v["id"] . '&nickname=' . $v["nickname"] . '&parent_user_id='.$v["parent_user_id"].'] ---Ended');
                    \app\common\model\User::where(["id"=>$v["parent_user_id"]])->update(["parent_user_id"=>0]);*/
                    continue;
                }
                $arr = array_merge($arr, [$v["id"]]);
                $this->find($v["id"], $v["parent_user_id"], $arr);
            }
        }
        dump($arr);
        die();
    }
}
